package dobest.ray.com.jiongjiong.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dobest.ray.corelibs.utils.DisplayUtil;
import com.dobest.ray.corelibs.utils.Tools;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import dobest.ray.com.jiongjiong.R;
import dobest.ray.com.jiongjiong.bean.RecommendAd;

/**
 * 轮播广告碎片
 *
 * @author ZhuFan
 * @Copyright Copyright © 2014 蓝色互动. All rights reserved.
 * @Date: 2015-3-13
 */
public class RecommendAdFragment extends Fragment implements OnClickListener {

    /**
     * 广告轮播速度
     */
    public static final int SCROLL_SPEED = 4000;

    /**
     * 上下文
     */
    private Activity mActivity;

    /**
     * 页面控件
     */
    private ViewPager vp_ads;
    private LinearLayout ll_dots;

    /**
     * 存储广告信息
     */
    private List<RecommendAd> ads = new ArrayList<RecommendAd>();

    /**
     * 存储广告图片
     */
    private List<ImageView> images;
    /**
     * 存储标识广告的圆点
     */
    private List<View> dots;
    /**
     * 广告数量
     */
    private int count = 1;
    /**
     * 用于自动轮播
     */
    private Handler handler;

    private RelativeLayout rl_dot_bg;
    private TextView tv_activity_time;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mActivity = getActivity();


        return inflater.inflate(R.layout.fragment_recommend_ad, container, false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        findViews(view);
        init();
        addListeners();
        super.onViewCreated(view, savedInstanceState);
    }

    /**
     * 初始化页面控件
     *
     * @param view
     * @return void
     * @throws @Date 2015-3-13 上午10:06:21
     * @author ZhuFan
     * @Package com.bm.jinzaitong.fragment
     */
    private void findViews(View view) {
        vp_ads = (ViewPager) view.findViewById(R.id.vp_ads);
        ll_dots = (LinearLayout) view.findViewById(R.id.ll_dots);
        rl_dot_bg = (RelativeLayout) view.findViewById(R.id.rl_dot_bg);
        tv_activity_time = (TextView) view.findViewById(R.id.tv_activity_time_ad);

    }

    /**
     * 初始化碎片
     *
     * @return void
     * @throws @Date 2015-3-13 上午10:06:34
     * @author ZhuFan
     * @Package com.bm.jinzaitong.fragment
     */
    private void init() {
        ads.clear();
        handler = new Handler();
        // 在加载数据后再加载view
        ads.add(new RecommendAd(R.mipmap.img_mu_pager_one));
        ads.add(new RecommendAd(R.mipmap.img_mu_pager_two));
        initViews();
        initViewPager();
    }


    private void addListeners() {
    }

    /**
     * 根据广告数量初始化图片以及小圆点
     *
     * @return void
     * @throws @Date 2015-3-13 上午10:06:54
     * @author ZhuFan
     * @Package com.bm.jinzaitong.fragment
     */
    private void initViews() {
        count = ads.size();

        images = new ArrayList<ImageView>();
        dots = new ArrayList<View>();

        for (int i = 0; i < count; i++) {
            View view = buildChildView();
            ll_dots.addView(view);
            dots.add(view);
        }

        for (int i = 0; i < count; i++) {
            ImageView imageView = new ImageView(mActivity);
            imageView.setTag(ads.get(i));
            imageView.setOnClickListener(this);
            if (Tools.isNull(ads.get(i).image)) {
                Picasso.with(mActivity).load(ads.get(i).resId).into(imageView);
            } else {
                Picasso.with(mActivity).load(ads.get(i).image).into(imageView);
            }


            imageView.setScaleType(ScaleType.FIT_XY);
            images.add(imageView);
        }
    }

    /**
     * 初始化ViewPager
     *
     * @return void
     * @throws @Date 2015-3-13 上午10:07:20
     * @author ZhuFan
     * @Package com.bm.jinzaitong.fragment
     */
    private void initViewPager() {
        vp_ads.setAdapter(new RecommendAdAdapter());
        vp_ads.setOnPageChangeListener(new RecommendAdPageChangedListener());
        vp_ads.setCurrentItem(0);
        dots.get(0).setBackgroundResource(R.mipmap.dot_focused);
        handler.postDelayed(runnable, SCROLL_SPEED);
    }

    /**
     * 生成小圆点
     *
     * @return View
     * @throws @Date 2015-3-13 上午10:07:30
     * @author ZhuFan
     * @Package com.bm.jinzaitong.fragment
     */
    private View buildChildView() {
        View view = new View(mActivity);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DisplayUtil.dip2px(mActivity, 8),
                DisplayUtil.dip2px(mActivity, 8));
        view.setBackgroundResource(R.mipmap.dot_normal);
        lp.setMargins(DisplayUtil.dip2px(mActivity, 2), 0, DisplayUtil.dip2px(mActivity, 2), 0);
        view.setLayoutParams(lp);

        return view;
    }

    /**
     * 监听器
     *
     * @author ZhuFan
     * @Copyright Copyright © 2014 蓝色互动. All rights reserved.
     * @Date: 2015-3-13
     */
    class RecommendAdPageChangedListener implements OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {

            handler.removeCallbacks(runnable);

            int position = arg0 % count;
            for (int i = 0; i < count; i++) {
                if (i == position)
                    dots.get(i).setBackgroundResource(R.mipmap.dot_focused);
                else
                    dots.get(i).setBackgroundResource(R.mipmap.dot_normal);
            }

            handler.postDelayed(runnable, SCROLL_SPEED);
        }

    }

    /**
     * 用于自动轮播的线程体
     */
    private Runnable runnable = new Runnable() {

        @Override
        public void run() {

            int current = vp_ads.getCurrentItem();
            vp_ads.setCurrentItem(current + 1);

        }
    };

    /**
     * 用于存储当页面被添加或删除时的position 当页面个数为3的时候, 无限轮播会出现bug, 必须在destroyItem中判断
     * 当Math.abs(add - remove) == 0的时候不删除页面, 不然会出现空页面的情况
     */
    private int add, remove = 0;

    /**
     * 适配器
     *
     * @author ZhuFan
     * @Copyright Copyright © 2014 蓝色互动. All rights reserved.
     * @Date: 2015-3-13
     */
    class RecommendAdAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return count < 3 ? count : Integer.MAX_VALUE;
        }

        @Override
        public Object instantiateItem(View container, int position) {
            int i = position % count;
            add = i;
            if (images.get(i).getParent() != null) {
                ((ViewPager) images.get(i).getParent()).removeView(images.get(i));
            }
            ((ViewPager) container).addView(images.get(i));
            return images.get(i);
        }

        @Override
        public void destroyItem(View arg0, int position, Object arg2) {
            int i = position % count;
            remove = i;
            if (count == 3 && Math.abs(add - remove) == 0)
                return;
            ((ViewPager) arg0).removeView(images.get(i));
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

    }

    /**
     * 页面暂停时取消轮播
     */
    @Override
    public void onPause() {
        handler.removeCallbacks(runnable);
        super.onPause();
    }

    /**
     * 页面恢复时注册轮播
     */
    @Override
    public void onResume() {
        handler.postDelayed(runnable, SCROLL_SPEED);
        super.onResume();
    }

    @Override
    public void onClick(View v) {
//		if (v instanceof ImageView) {}

    }


}
